<?php

namespace App\Admin\Actions\Grid;

use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BatchCommentAction extends BatchAction
{
    /**
     * @return string
     */
	protected $title = '审核通过';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $ids = $this->getKey();

        foreach ($ids as $id){
            DB::transaction(function () use ($id){
                $comment = WxComment::where([['id', '=', $id], ['comment_state', '!=', 1]])->first();

                if($comment){
                    $uid = $comment->user_id;
                    $posts_id = $comment->posts_id;
                    $msg = UserUtils::reward_user_coin($uid, 'comment');
                    if($msg){
                        UserUtils::add_user_notice(3001, $uid,'评论审核通知','您发表的评论(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$id.'</a>)已经审核通过，并获得评论奖励：'.$msg,100);
                    }else {
                        UserUtils::add_user_notice(3001, $uid, '评论审核通知', '您发表的评论(id:<a href="/pages/sticky/sticky?id=' . $posts_id . '">' . $id . '</a>)已经审核通过', 100);
                    }
                    WxComment::where('id',$id)->update(['comment_state'=>1]);

                    $comment_count = WxCommentRepositores::commentCount($comment->posts_id) ?: 0;//评论数量
                    $weight = WxPost::where('id', $comment->posts_id)->value('weight');
                    $weight += ( Utils::getDecayCoefficient($comment_count, 5) * 1000);
                    if($weight > time()){
                        $weight = time();
                    }
                    WxPost::withoutSyncingToSearch(function () use ($comment,$weight){
                        WxPost::where('id', $comment->posts_id)->update(['last_reply_at' => $comment->created_at, 'weight'=>timetostr($weight)]);
                    });

                }

            });
        }

        return $this->response()
            ->success('Processed successfully: '.json_encode($this->getKey()))->refresh();
    }

    /**
	 * @return string|array|void
	 */
	public function confirm()
	{
        return ['确认审核通过?'];
	}

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}
